package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.listener.BasicExcelListener;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Ksda;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Yfd;
import cn.stylefeng.guns.sys.modular.system.entity.BtyCrk;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyCrkMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyCrkParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyCrkDto;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyCrkResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyCrkService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;


/**
 * 控制器
 *
 * @author liuy
 * @Date 2021-12-10 11:30:01
 */
@Controller
@RequestMapping("/btyCrk")
public class BtyCrkController extends BaseController {

    private String PREFIX = "/modular/system/btyCrk";

    @Autowired
    private BtyCrkService btyCrkService;

    @Resource
    private BtyCrkMapper crkMapper;

    /**
     * 跳转到主页面
     *
     * @author liuy
     * @Date 2021-12-10
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyCrk.html";
    }

    /**
     * 新增页面
     *
     * @author liuy
     * @Date 2021-12-10
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyCrk_add.html";
    }

    /**
     * 编辑页面
     *
     * @author liuy
     * @Date 2021-12-10
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyCrk_edit.html";
    }

    /**
     * 新增接口
     *
     * @author liuy
     * @Date 2021-12-10
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyCrkParam btyCrkParam) {
        this.btyCrkService.add(btyCrkParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author liuy
     * @Date 2021-12-10
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyCrkParam btyCrkParam) {
        this.btyCrkService.update(btyCrkParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author liuy
     * @Date 2021-12-10
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyCrkParam btyCrkParam) {
        this.btyCrkService.delete(btyCrkParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author liuy
     * @Date 2021-12-10
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyCrkParam btyCrkParam) {
        BtyCrk detail = this.btyCrkService.getById(btyCrkParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author liuy
     * @Date 2021-12-10
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyCrkParam btyCrkParam) {
        return this.btyCrkService.findPageBySpec(btyCrkParam);
    }

    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object addUsers(@RequestParam("file") MultipartFile file) {
        JsonResult jsonResult = new JsonResult();
        //导入之前删掉之前的数据
        crkMapper.delete(new QueryWrapper<>());
        try {
            BasicExcelListener basicExcelListener = new BasicExcelListener(btyCrkService);
            EasyExcel.read(file.getInputStream(), BtyCrkDto.class, basicExcelListener).sheet(0).headRowNumber(4).doRead();
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return true;
    }

    /**
     * 查询收发类别
     */
    @RequestMapping(value = "/getSflb")
    @ResponseBody
    public List<BtyCrk> getSflb() {
        List<BtyCrk> list = btyCrkService.sflbList();
        return list;
    }

    /**
     * 配送凭证
     */
    @RequestMapping(value = "/pz")
    @ResponseBody
    public Object zcpz(BtyCrkParam param) {
        //用友制单日期
        String zdrq = param.getZdrq();
        //根据收发类别分组获取门店的金额
        String sflb = param.getSflb();
        String zy = "";
        if (ToolUtil.isNotEmpty(sflb) && sflb.equals("中心统配出库")) {
            zy = "发货单";
        } else if (ToolUtil.isNotEmpty(sflb) && sflb.equals("外销出库")) {
            zy = "外销单";
        } else if (ToolUtil.isNotEmpty(sflb) && sflb.equals("调拨出库")) {
            zy = "中心间调出单";
        } else if (ToolUtil.isNotEmpty(sflb) && sflb.equals("采购退货")) {
            zy = "采购退货";

        } else if (ToolUtil.isNotEmpty(sflb) && sflb.equals("中心统配返库")) {
            zy = "退货单";
        } else if (ToolUtil.isNotEmpty(sflb) && sflb.equals("外销退货")) {
            zy = "外销退货";
        }
        String bh = "201";
        if (ToolUtil.isNotEmpty(sflb) && sflb.equals("中心统配返库")) {
            List<BtyCrkResult> fkList = btyCrkService.tpfkList();
            for (BtyCrkResult btyCrkResult : fkList) {
                BigDecimal je = btyCrkResult.getZdy4();
                String ksbm = "";
                String dm = btyCrkResult.getGys();

                //根据店名查询客商辅助核算编码
                String json = "{\"custname\":\"" + dm + "\"}";
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("trantype", "code"); // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("system", "001"); // 系统编码
                headers.add("usercode", "15253172037"); // 用户
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                HttpEntity<String> formEntitys = new HttpEntity<String>(json, headers);
                String urls = "http://124.70.28.147:8089/u8cloud/api/uapbd/custdoc/query";

                Yfd yfd = restTemplate.postForEntity(urls, formEntitys, Yfd.class).getBody();
                JSONObject resultObject = JSON.parseObject(yfd.getData());
                JSONArray jsonArray = resultObject.getJSONArray("datas");
                JSONObject jsonObject;
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        jsonObject = jsonArray.getJSONObject(0);
                        Ksda.DatasBean.ParentvoBean parentvo = jsonObject.getObject("parentvo", Ksda.DatasBean.ParentvoBean.class);
                        ksbm = parentvo.getCustcode();
                    }
                }
                if(dm.equals("东营广饶博兴啤酒直通")){
                    ksbm="020600014";
                }else if(dm.equals("博兴啤酒直通")){
                    ksbm="020600130";
                }

                StringBuilder sb = new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");
                    sb.append(
                            "{\n" +
                                    "\t\t\t\t\"ass\":[\n" +
                                    "                        {\n" +
                                    "                            \"checktypecode\":\"73\",\n" +
                                    "                            \"checkvaluecode\":'" + ksbm + "'\n" +//客商辅助核算编码
                                    "                        },\n" +
                                    "                    ],\n" +
                                    "                    \"creditamount\":\"\",\n" +
                                    "                    \"creditquantity\":\"\",\n" +
                                    "                    \"debitamount\":\"" + je + "\",\n" +//借方金额
                                    "                    \"debitquantity\":\"\",\n" +
                                    "                    \"detailindex\":\"\",\n" +
                                    "                    \"excrate1\":\"\",\n" +
                                    "                    \"explanation\":\"" + zy + "\",\n" +//借方摘要
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"1122\",\n" +//借方科目编码
                                    "                    \"pk_currtype\":\"CNY\",\n" +
                                    "                    \"price\":\"\"\n" +
                                    "                },\n" +
                                    "                {\n" +
                                    "                    \"creditamount\":\"" + je + "\",\n" +//贷方金额
                                    "                    \"debitamount\":\"\",\n" +
                                    "                    \"explanation\":\"" + zy + "\",\n" +//贷方摘要
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"6001\",\n" +//贷方科目编码
                                    "                    \"pk_currtype\":\"CNY\"\n" +
                                    "                },");
                sb.append("            ],\n" +
                        "            \"pk_corp\":" + bh + ",\n" +
                        "            \"pk_glorgbook\":\"" + bh + "-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\"" + zdrq + "\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}");

                //System.out.println("sb:"+sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                //System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取status对应的值
                String status = jo.get("status").getAsString();

                if (status.equals("falied")) {
                    String errormsg = jo.get("errormsg").getAsString();
                    System.out.println("errormsg:" + errormsg);
                    //return ResponseData.error(501,errormsg);
                }
            }
        }

        else {
            List<BtyCrkResult> list = btyCrkService.gysList(param);
            for (BtyCrkResult crkResult : list) {
                BigDecimal je = crkResult.getZdy4();
                String ksbm = "";
                String dm = crkResult.getGys();

                //根据店名查询客商辅助核算编码
                String json = "{\"custname\":\"" + dm + "\"}";
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("trantype", "code"); // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("system", "001"); // 系统编码
                headers.add("usercode", "15253172037"); // 用户
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                HttpEntity<String> formEntitys = new HttpEntity<String>(json, headers);
                String urls = "http://124.70.28.147:8089/u8cloud/api/uapbd/custdoc/query";

                Yfd yfd = restTemplate.postForEntity(urls, formEntitys, Yfd.class).getBody();
                JSONObject resultObject = JSON.parseObject(yfd.getData());
                JSONArray jsonArray = resultObject.getJSONArray("datas");
                JSONObject jsonObject;
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        jsonObject = jsonArray.getJSONObject(0);
                        Ksda.DatasBean.ParentvoBean parentvo = jsonObject.getObject("parentvo", Ksda.DatasBean.ParentvoBean.class);
                        ksbm = parentvo.getCustcode();
                    }
                }
                if(dm.equals("东营广饶博兴啤酒直通")){
                    ksbm="020600014";
                }else if(dm.equals("博兴啤酒直通")){
                    ksbm="020600130";
                }

                StringBuilder sb = new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");
                if (ToolUtil.isNotEmpty(sflb) && sflb.equals("采购退货")) {
                    //借倒挤差额是自定义项5-成本价
                    BigDecimal thje = crkResult.getZdy5();
                    BigDecimal rkje = crkResult.getRkje();
                    BigDecimal ce = thje.subtract(rkje);
                    //BigDecimal ce=rkje.subtract(thje);
                    sb.append(
                            "                {\n" +
                                    "                    \"creditamount\":\"\",\n" +
                                    "                    \"debitamount\":\"" + rkje + "\",\n" +//借方金额
                                    "                    \"explanation\":\"" + zy + "\",\n" +//借方摘要
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"1403\",\n" +//借方科目编码
                                    "                    \"pk_currtype\":\"CNY\"\n" +
                                    "                },");

                    if (ce.compareTo(BigDecimal.ZERO) == 1 | ce.compareTo(BigDecimal.ZERO) == -1) {
                        sb.append("{\n" +
                                "                    \"creditamount\":\"\",\n" +
                                "                    \"creditquantity\":\"\",\n" +
                                "                    \"debitamount\":\"" + ce + "\",\n" +//借方金额
                                "                    \"debitquantity\":\"\",\n" +
                                "                    \"detailindex\":\"\",\n" +
                                "                    \"excrate1\":\"\",\n" +
                                "                    \"explanation\":\"" + zy + "\",\n" +//借方摘要
                                "                    \"localcreditamount\":\"\",\n" +
                                "                    \"localdebitamount\":\"\",\n" +
                                "                    \"pk_accsubj\":\"6401\",\n" +//主营业务成本科目编码
                                "                    \"pk_currtype\":\"CNY\",\n" +
                                "                    \"price\":\"\"\n" +
                                "                },\n");
                    }
                    sb.append(
                            "{\n" +
                                    "\t\t\t\t\"ass\":[\n" +
                                    "                        {\n" +
                                    "                            \"checktypecode\":\"73\",\n" +
                                    "                            \"checkvaluecode\":'" + ksbm + "'\n" +//客商辅助核算编码
                                    "                        },\n" +
                                    "                    ],\n" +
                                    "                    \"creditamount\":\"" + thje + "\",\n" +//贷方金额
                                    "                    \"creditquantity\":\"\",\n" +
                                    "                    \"debitamount\":\"\",\n" +
                                    "                    \"debitquantity\":\"\",\n" +
                                    "                    \"detailindex\":\"\",\n" +
                                    "                    \"excrate1\":\"\",\n" +
                                    "                    \"explanation\":\"" + zy + "\",\n" +//贷方摘要
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"2202\",\n" +//贷方科目编码
                                    "                    \"pk_currtype\":\"CNY\",\n" +
                                    "                    \"price\":\"\"\n" +
                                    "                },\n");

                } else {
                    sb.append(
                            "{\n" +
                                    "\t\t\t\t\"ass\":[\n" +
                                    "                        {\n" +
                                    "                            \"checktypecode\":\"73\",\n" +
                                    "                            \"checkvaluecode\":'" + ksbm + "'\n" +//客商辅助核算编码
                                    "                        },\n" +
                                    "                    ],\n" +
                                    "                    \"creditamount\":\"\",\n" +
                                    "                    \"creditquantity\":\"\",\n" +
                                    "                    \"debitamount\":\"" + je + "\",\n" +//借方金额
                                    "                    \"debitquantity\":\"\",\n" +
                                    "                    \"detailindex\":\"\",\n" +
                                    "                    \"excrate1\":\"\",\n" +
                                    "                    \"explanation\":\"" + zy + "\",\n" +//借方摘要
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"1122\",\n" +//借方科目编码
                                    "                    \"pk_currtype\":\"CNY\",\n" +
                                    "                    \"price\":\"\"\n" +
                                    "                },\n" +
                                    "                {\n" +
                                    "                    \"creditamount\":\"" + je + "\",\n" +//贷方金额
                                    "                    \"debitamount\":\"\",\n" +
                                    "                    \"explanation\":\"" + zy + "\",\n" +//贷方摘要
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"6001\",\n" +//贷方科目编码
                                    "                    \"pk_currtype\":\"CNY\"\n" +
                                    "                },");
                }
                sb.append("            ],\n" +
                        "            \"pk_corp\":" + bh + ",\n" +
                        "            \"pk_glorgbook\":\"" + bh + "-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\"" + zdrq + "\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}");

                System.out.println("sb:" + sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                //System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取status对应的值
                String status = jo.get("status").getAsString();

                if (status.equals("falied")) {
                    String errormsg = jo.get("errormsg").getAsString();
                    // List<BtyCrk> lists= baseMapper.selectOne(new QueryWrapper<BtyShdkmx>().eq("dm", dm));
                    List<BtyCrk> lists = btyCrkService.list(new QueryWrapper<BtyCrk>().eq("gys", dm).eq("sflb", sflb));
                    if (lists.size() > 0) {
                        BtyCrkParam param1 = new BtyCrkParam();
                        param1.setGys(dm);
                        param1.setSflb(sflb);
                        param1.setErrormsg(errormsg);
                        btyCrkService.updateErrMsgByDm(param1);
                    }

                    System.out.println("errormsg:" + errormsg);
                    //return ResponseData.error(501,errormsg);
                } else {
                    List<BtyCrk> lists = btyCrkService.list(new QueryWrapper<BtyCrk>().eq("gys", dm).eq("sflb", sflb));
                    if (lists.size() > 0) {
                        BtyCrkParam param1 = new BtyCrkParam();
                        param1.setGys(dm);
                        param1.setSflb(sflb);
                        btyCrkService.updateByDm(param1);
                    }
                }

            }
        }
        return ResponseData.success();
    }

}


